<?php

namespace app\beautiful\model\setting;

use app\beautiful\model\member\MemberModel;
use app\common\model\CommonModel;
use think\facade\Db;


class ConsumeBonusModel extends CommonModel{

    protected  $name = 'beautiful_consume_bonus';

    protected  $pk   = 'consume_bonus_id';

    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public static function memberlist($where,$owhere,$bowhere,$order,$page=1,$limit=10,$member_ids){
        $query = Db::name('beautiful_member')->alias('m')
            ->join('wyu_beautiful_order o','m.member_id=o.member_id')
            ->join('wyu_beautiful_buy_order bo','m.member_id=bo.member_id')
            ->where($where)
            ->where($owhere)
            ->where($bowhere)
            ->group('m.member_id')
            ->field('sum(o.need_pay) as total_price,m.member_id,m.nick_name,m.face,m.mobile,sum(o.need_pay)+sum(bo.pay_money) as total_need_pay,count(o.order_id)+count(bo.buy_order_id) as order_count');

        $count = $query->count();
        $list = $query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                $list[$k]['label'] = $v['order_count']>1?'多次复购，老客户':'新客户';//标签
                $list[$k]['is_selected'] = in_array($v['member_id'],$member_ids)?1:0;//是否入围
                $list[$k]['sort'] = ($page-1) * $limit + ($k+1);
                $list[$k]['total_need_pay'] = sprintf("%.2f",$v['total_need_pay']);
            }
        }
        return compact('count','list');
    }


}

